package com.example.gulimall.order.rabbit.listener;

import com.example.common.config.rabbit.common.RabbitTemplateWrapper;
import com.example.common.config.rabbit.order.OrderTransactionalConfig;
import com.example.common.constant.MessageConstant;
import com.example.common.constant.RabbitContent;
import com.example.common.entity.order.OrderEntity;
import com.example.gulimall.order.service.OrderService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;

/**
 * <p>
 *      订单关闭处理器
 * </p>
 *
 * @author zyred
 * @since v 0.1
 **/
@Slf4j
@Configuration
@RabbitListener(queues = OrderTransactionalConfig.NORMAL_QUEUE)
public class OrderReleaseRabbitListener {

    @Autowired private OrderService orderService;
    @Autowired private RabbitTemplateWrapper rabbitTemplateWrapper;

    @RabbitHandler
    public void releaseOrder (OrderEntity order, Channel channel, Message message) throws IOException {

        log.info(">>>>>>>>>>>>>>>>>>> 监听到过期订单 <<<<<<<<<<<<<<<<<<");
        log.info("订单号：{}", order.getOrderSn());
        log.info("订单创建时间：{}", order.getCreateTime());
        log.info(">>>>>>>>>>>>>>>>>>> 监听到过期订单 <<<<<<<<<<<<<<<<<<");

        long tag = message.getMessageProperties().getDeliveryTag();
        String id =  (String) message.getMessageProperties().getHeaders().get(RabbitContent.RABBIT_KEY);

        try {
            this.orderService.releaseOrder (order);
            channel.basicAck(tag, true);

            // 消费成功后，将消息修改为成功状态
            this.rabbitTemplateWrapper.alertStatusAsync(
                    MessageConstant.MessageStatus.SPENDING.getCode(),
                    null, id);

        } catch (Exception ex) {
            ex.printStackTrace();
            channel.basicReject(tag, true);

            // 消费失败后，将消息修改为失败状态
            this.rabbitTemplateWrapper.alertStatusAsync(
                    MessageConstant.MessageStatus.SPENDING_ERROR.getCode(),
                    ex.getMessage(),  id);
        }

    }

}
